using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using System.Runtime.InteropServices;
using PowerShell2R.Interop;

namespace PowerShell2R.PowerShell
{
    [Cmdlet("Eval", "R")]
    public class RCmdlet : PSCmdlet
    {
        private string[] _expression;
        private PSObject _data;
        private List<PSObject> _dataList = new List<PSObject>();

        #region Parameters
        [Parameter(Position = 0,
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "R Expression")]
        [ValidateNotNullOrEmpty]
        public string[] Expression
        {
            set { _expression = value; }
        }

        [Parameter(
           Position = 1,
           ValueFromPipeline = true,
           ValueFromPipelineByPropertyName = false)]
        [ValidateNotNullOrEmpty]
        public PSObject Data
        {
            get { return _data; }
            set { _data = value; }
        }
        #endregion

        protected override void BeginProcessing()
        {
        }

        protected override void ProcessRecord()
        {   
            _dataList.Add(_data);
        }

        protected override void EndProcessing()
        {
            using(RInterop interop = new RInterop(_dataList))
            {
                foreach (string expr in _expression)
                {
                    WriteObject(interop.Evaluate(expr));
                }
            }
        }
    }
}
